const express = require('express');
const router = express.Router();
const configService = require('../services/configService');
const { authenticateToken, requireAdmin } = require('../middleware/auth');

// 获取所有配置（管理员权限）
router.get('/', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const configs = await configService.getAllConfigs();
    res.json({
      success: true,
      data: configs
    });
  } catch (error) {
    console.error('获取配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取配置失败',
      error: error.message
    });
  }
});

// 获取特定配置值
router.get('/:key', authenticateToken, async (req, res) => {
  try {
    const { key } = req.params;
    const value = await configService.getConfig(key);
    
    if (value === undefined) {
      return res.status(404).json({
        success: false,
        message: '配置项不存在'
      });
    }
    
    res.json({
      success: true,
      data: {
        key,
        value
      }
    });
  } catch (error) {
    console.error('获取配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取配置失败',
      error: error.message
    });
  }
});

// 更新配置值（管理员权限）
router.put('/:key', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const { key } = req.params;
    const { value, type = 'string' } = req.body;
    
    if (value === undefined) {
      return res.status(400).json({
        success: false,
        message: '配置值不能为空'
      });
    }
    
    await configService.updateConfig(key, value, type);
    
    res.json({
      success: true,
      message: '配置更新成功',
      data: {
        key,
        value
      }
    });
  } catch (error) {
    console.error('更新配置失败:', error);
    res.status(500).json({
      success: false,
      message: '更新配置失败',
      error: error.message
    });
  }
});

// 批量更新配置（管理员权限）
router.put('/', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const { configs } = req.body;
    
    if (!Array.isArray(configs)) {
      return res.status(400).json({
        success: false,
        message: '配置数据格式错误'
      });
    }
    
    const results = [];
    for (const config of configs) {
      try {
        await configService.updateConfig(config.key, config.value, config.type);
        results.push({
          key: config.key,
          success: true
        });
      } catch (error) {
        results.push({
          key: config.key,
          success: false,
          error: error.message
        });
      }
    }
    
    res.json({
      success: true,
      message: '批量更新完成',
      data: results
    });
  } catch (error) {
    console.error('批量更新配置失败:', error);
    res.status(500).json({
      success: false,
      message: '批量更新配置失败',
      error: error.message
    });
  }
});

// 清除配置缓存（管理员权限）
router.post('/clear-cache', authenticateToken, requireAdmin, async (req, res) => {
  try {
    configService.clearCache();
    res.json({
      success: true,
      message: '配置缓存已清除'
    });
  } catch (error) {
    console.error('清除缓存失败:', error);
    res.status(500).json({
      success: false,
      message: '清除缓存失败',
      error: error.message
    });
  }
});

// 获取特定分类的配置
router.get('/category/:category', authenticateToken, async (req, res) => {
  try {
    const { category } = req.params;
    const allConfigs = await configService.getAllConfigs();
    const categoryConfigs = allConfigs[category] || {};
    
    res.json({
      success: true,
      data: categoryConfigs
    });
  } catch (error) {
    console.error('获取分类配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类配置失败',
      error: error.message
    });
  }
});

// 获取系统状态（包括配置加载状态）
router.get('/status/health', async (req, res) => {
  try {
    const configCount = configService.configCache.size;
    const lastUpdate = configService.lastCacheUpdate;
    const cacheAge = Date.now() - lastUpdate;
    
    res.json({
      success: true,
      data: {
        configCount,
        lastUpdate: new Date(lastUpdate).toISOString(),
        cacheAge: Math.floor(cacheAge / 1000), // 秒
        cacheExpiry: Math.floor(configService.cacheExpiry / 1000) // 秒
      }
    });
  } catch (error) {
    console.error('获取配置状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取配置状态失败',
      error: error.message
    });
  }
});

module.exports = router;
